package cn.darkhorse.workflow.service.impl;


import cn.darkhorse.workflow.auto.entity.BpmnAgent;
import cn.darkhorse.workflow.auto.entity.BpmnSysUser;
import cn.darkhorse.workflow.auto.entity.ProjectApprovalOpinions;
import cn.darkhorse.workflow.auto.service.IBpmnAgentService;
import cn.darkhorse.workflow.core.WorkflowType;
import cn.darkhorse.workflow.service.IApprovalService;
import cn.darkhorse.workflow.service.IWorkflowToolService;
import cn.darkhorse.workflow.tool.WorkflowConstants;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @description:
 * @author: mr.wang
 * @time: 2020/7/6 0006 14:19
 */
@Service
public class ApprovalServiceImpl implements IApprovalService {
	
	
	
	
	@Autowired
	IWorkflowToolService iWorkflowToolService;
	@Resource
	IBpmnAgentService bpmnAgentService;

	
	/**
	 * 选取可发起的流程
	 * @param typeId
	 */
	@Override
	public List<Map<String,Object>> chooseWorkflow(String typeId,String userName) {
		return iWorkflowToolService.getWorkflow(typeId,userName);
	}
	
	
	/**
	 * 待办事项（临时）
	 * @param userName
	 */
	@Override
	public List<Map<String,Object>> selectSchedule(String userName) {
		//代办事项名称集
		Map<String, String> bpmnAgent = getBpmnAgent();
		List<Map<String,Object>> schedules = iWorkflowToolService.getSchedule(userName);
		List<Map<String,Object>> dataSchedules=new ArrayList<>();
		Map<String, String> transHistory = iWorkflowToolService.getTransHistory(userName);

		if(schedules!=null&&schedules.size()>0&& null != bpmnAgent &&bpmnAgent.size()>0){
			for(Map<String,Object> schedule:schedules){
				schedule.put("businessName","");
				boolean b = isContain((String) schedule.get("businessType"));
				if(b){
					String key = (String)schedule.get("businessId")+ WorkflowType.valueOf((String)schedule.get("businessType")).getType();
					String name = bpmnAgent.get(key);
					if(StringUtils.isNotBlank(name)){
						schedule.put("businessName",name);
					}
				}
				if(!transHistory.containsKey(schedule.get("taskId")+"-"+schedule.get("processInstanceId"))){
					dataSchedules.add(schedule);
				}
			}
		}
		return dataSchedules;
	}
	
	/**
	 * 枚举类是否包含
	 * @param type  待校验字段
	 * @return
	 */
	private boolean isContain(String type){
		WorkflowType[] values = WorkflowType.values();
		for(int i = 0 ; i<values.length;i++){
			if(type.equals(values[i].name())){
				return true;
			}
		}
		return false;
	}
	
	
	
	/**
     * 代办事项名称结果集
	 * @return
	 */
	private Map<String,String> getBpmnAgent(){
		Map<String,String> result = new HashMap<>();
		List<BpmnAgent> agentList = bpmnAgentService.list();
		agentList.forEach(item->{
			String key = String.valueOf(item.getBusinessId())+item.getBusinessType();
			result.put(key,item.getBusinessName());
		});
		return result;
	}
	
	
	
	/**
	 * 查询审批表意见
	 * @param businessId
	 * @return
	 */
	@Override
	public List<ProjectApprovalOpinions> getApprovalFormInfo(String businessId, String businessType) {
		return iWorkflowToolService.getApprovalFormInfo(businessId,businessType);
	}

	@Override
	public List<ProjectApprovalOpinions> getApprovalFormInfo2(String businessId, String businessType) {
		return iWorkflowToolService.getApprovalFormInfo2(businessId,businessType);
	}

	/**
	 * 获取审批权限（同意，不同意，否决）
	 * @param taskKey
	 * @return
	 */
	@Override
	public Map<String, Object> getApprovalAuthority(String taskKey,String taskId,String workflowExampleId) {
		return iWorkflowToolService.getApprovalAuthority(taskKey,taskId,workflowExampleId);
	}
	
	/**
	 * 流程图
	 * @param businessId
	 * @param businessType
	 * @return
	 */
	@Override
	public Map<String,Object> getFlowChart(Long businessId, String businessType,String workflowExampleId) {
		return iWorkflowToolService.getFlowChart(businessId,businessType,workflowExampleId);
	}
	
	@Override
	public JSONArray getNextNode(String workFlowId, String businessId, String businessType, List<BpmnSysUser> users) {
		//停用用户
		List<String> stopUsers = stopUsers(users);
		//昵称
		Map<String, String> nickUsers = nickUsers(users);
		
		Set<String> repert = new HashSet<>();
		JSONArray nextNodes = new JSONArray();
		JSONArray nextNodeHandlers = iWorkflowToolService.getNextNodeHandlers(workFlowId, businessId, businessType, null);
		if(nextNodeHandlers != null && nextNodeHandlers.size()>0){
			for(int i = 0 ; i<nextNodeHandlers.size();i++){
				JSONObject jsonObject = nextNodeHandlers.getJSONObject(i);
				String person = jsonObject.getString("responsible_person");
				String approver = person;
				//昵称翻译
				if(nickUsers.size()>0){
					String nickName = nickUsers.get(person);
					if(StringUtils.isNotBlank(nickName)){
						approver = nickName;
					}
				}
				jsonObject.put("responsible_person",approver);
				//是否停用用户
				boolean contains = stopUsers.contains(person);
				if(repert.add(person)){
					if(contains){
						jsonObject.put("responsible_person",approver+"(已停用)");
					}
					nextNodes.add(jsonObject);
				}
				
			}
		}
		return nextNodes;
		//return iWorkflowToolService.getNextNodeHandlers(workFlowId,businessId,businessType,null);
	}
	
	/**
	 * 停用用户
	 * @param users
	 * @return
	 */
	private List<String> stopUsers (List<BpmnSysUser> users){
		List<String> stopUsers = new ArrayList<>();
			users.forEach(item->{
				if(WorkflowConstants.USER_DISABLE.equals(item.getStatus())){
					stopUsers.add(item.getUserName());
				}
			});
		return stopUsers;
	}
	/**
	 * 用户昵称
	 * @param users
	 * @return
	 */
	private Map<String,String> nickUsers (List<BpmnSysUser> users){
		Map<String,String> nickMap = new HashMap<>();
			users.forEach(item->{
				nickMap.put(item.getUserName(),item.getNickName());
			});
		return nickMap;
	}
	
	
	
	
}
